package com.lx.pc.restful.wx;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.ocr.BankCardutils;
import com.aliyun.ocr.CardUtils;
import com.aliyun.ocr.DrivingUtils;
import com.aliyuncs.exceptions.ClientException;
import com.lx.pc.baidu.ueditor.define.FileType;
import com.lx.pc.domain.vo.account.AccountVo;
import com.lx.pc.domain.vo.accountlog.AccountLogVo;
import com.lx.pc.domain.vo.bankcardinfo.BankcardInfoVo;
import com.lx.pc.domain.vo.card.CardVo;
import com.lx.pc.domain.vo.driving.DrivingVo;
import com.lx.pc.domain.vo.opinion.OpinionVo;
import com.lx.pc.domain.vo.paypass.PayPassVo;
import com.lx.pc.domain.vo.sms.SmsVo;
import com.lx.pc.domain.vo.user.UserVo;
import com.lx.pc.domain.vo.worder.WOrderVo;
import com.lx.pc.domain.vo.wordercategory.WOrderCategoryVo;
import com.lx.pc.domain.vo.wx.WeixinVo;
import com.lx.pc.restful.util.AjaxResult;
import com.lx.pc.restful.util.SmsMessage;
import com.lx.pc.service.account.IAccountService;
import com.lx.pc.service.accountlog.IAccountLogService;
import com.lx.pc.service.bankcardinfo.IBankcardInfoService;
import com.lx.pc.service.card.ICardService;
import com.lx.pc.service.driving.IDrivingService;
import com.lx.pc.service.opinion.IOpinionService;
import com.lx.pc.service.paypass.IPayPassService;
import com.lx.pc.service.sms.ISmsService;
import com.lx.pc.service.user.IUserService;
import com.lx.pc.service.wcategory.IWCategoryService;
import com.lx.pc.service.worder.IWOrderService;
import com.lx.pc.service.worderCategory.IWOrderCategoryService;
import com.lx.pc.service.worderprice.IWOrderPriceService;
import com.lx.pc.service.wx.IWeixinService;
import com.lx.pc.utils.Constants;
import com.lx.pc.utils.ImageOperation;
import com.lx.pc.utils.RandomUtils;
import com.lx.pc.utils.Utils;

/**
 * 回收员订单列表
 * @author houzhong
 */
@Controller
@RequestMapping("/wx")
public class ReceiptController {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(ReceiptController.class);
	
	/**
	 * 微信获取token
	 */
	@Resource(name = "weixinService")
	private IWeixinService weixinService;
	
	/**
	 * 用户
	 */
	@Resource(name = "userService")
	private IUserService userService;

	/**
	 * 用户订单
	 */
	@Resource(name = "wOrderService")
	private IWOrderService wOrderService;
	
	/**
	 * 用户多个分类多个重量
	 */
	@Resource(name = "wOrderCategoryService")
	private IWOrderCategoryService wOrderCategoryService;
	
	/**
	 * 定价
	 */
	@Resource(name = "wOrderPriceService")
	private IWOrderPriceService wOrderPriceService;
	
	/**
	 * 分类
	 */
	@Resource(name = "wCategoryService")
	private IWCategoryService wCategoryService;
	
	/**
	 * 短信
	 */
	@Resource(name = "smsService")
	private ISmsService smsService;
	
	/**
	 * 身份证
	 */
	@Resource(name = "cardService")
	private ICardService cardService;
	
	/**
	 * 行驶证
	 */
	@Resource(name = "drivingService")
	private IDrivingService drivingService;
	
	/**
	 * 意见反馈
	 */
	@Resource(name = "opinionService")
	private IOpinionService opinionService;
	
	/**
	 * 个人账户
	 */
	@Resource(name = "accountService")
	private IAccountService accountService;
	
	/**
	 * 支付密码设置
	 */
	@Resource(name = "payPassService")
	private IPayPassService payPassService;
	
	/**
	 * 银行卡
	 */
	@Resource(name = "bankcardInfoService")
	private IBankcardInfoService bankcardInfoService;
	
	/**
	 * 个人账户日志
	 */
	@Resource(name = "accountLogService")
	private IAccountLogService accountLogService;
	
	/**
	 * 订单数据
	 * @param request
	 * @param v
	 * @return
	 */
	@RequestMapping("/toReceiptOrderList")
	public ModelAndView toReceiptOrderList(HttpServletRequest request,UserVo v) throws Exception {
		ModelAndView mv = new ModelAndView("/wx/seller/home");

		String code = request.getParameter("code");
		System.out.println("order:code--------" + code);
		
		//获取公众号信息
		JSONObject jsonObject = WeiXinUtils.getUserInfo(code);
		
		//获取用户信息
		UserVo userVo = getOpenId(jsonObject);
		//UserVo userVo = userService.findByUsername(v);
		if (userVo.getNickName() == null) {
			//获取微信token
			WeixinVo weixinVo = weixinService.findByWeixin();
			//获取公众号信息
			String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+weixinVo.getAccessToken()+"&openid="+userVo.getWxOpenId()+"&lang=zh_CN";
			JSONObject jsonObject1 = WeiXinUtils.httpRequest(url, "GET", new JSONObject());
			//用户昵称
			String nickName = jsonObject1.getString("nickname");
			//获取用户默认头像
			String headimgurl = jsonObject1.getString("headimgurl");
			userVo.setUserImg(headimgurl);
			userVo.setNickName(nickName);
			
			userVo.setId(new BigInteger(userVo.getbId()));
			//获取用户头像修改
			userService.updateUser(userVo);
		}

		WOrderVo orderVo = new WOrderVo();
		orderVo.setReceiptId(userVo.getbId());
		Integer countNum = wOrderService.findByReceiptCount(orderVo);
		Float totalPrice = 0f;
		if (countNum != 0) {
			WOrderCategoryVo orderCategoryVo = new WOrderCategoryVo();
			orderCategoryVo.setReceiptId(userVo.getbId());
			totalPrice = wOrderCategoryService.findByTotalPriceCount(orderCategoryVo);
		}
		if (totalPrice == null) {
			totalPrice = 0f;
		}
		mv.addObject("userVo",userVo);
		//今日接单总数
		mv.addObject("countNum",countNum);
		//今日总价格
		mv.addObject("totalPrice",(float)(Math.round(totalPrice*100))/100);
		return mv;
	}
	
	/**
	 * 修改状态跳转到订单列表
	 * @param v
	 * @return
	 */
	@RequestMapping("/toReceiptList")
	public ModelAndView toReceiptList(UserVo v) throws Exception {
		ModelAndView mv = new ModelAndView("/wx/seller/home");
		UserVo userVo = userService.findByUsername(v);
		
		WOrderVo orderVo = new WOrderVo();
		orderVo.setReceiptId(userVo.getbId());
		Integer countNum = wOrderService.findByReceiptCount(orderVo);
		Float totalPrice = 0f;
		if (countNum != 0) {
			WOrderCategoryVo orderCategoryVo = new WOrderCategoryVo();
			orderCategoryVo.setReceiptId(userVo.getbId());
			totalPrice = wOrderCategoryService.findByTotalPriceCount(orderCategoryVo);
		}
		mv.addObject("userVo",userVo);
		//今日接单总数
		mv.addObject("countNum",countNum);
		//今日总价格
		mv.addObject("totalPrice",totalPrice);
		return mv;
	}
	
	/**
	 * 小程序 查询今日订单数和总价
	 * @param v
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("/toHomenCount.do")
    public  String toHomenCount(UserVo v) throws Exception {
        Map<String,Object> result = new HashMap<String, Object>();
        
        UserVo userVo = userService.findByUsername(v);
		
		WOrderVo orderVo = new WOrderVo();
		orderVo.setReceiptId(userVo.getbId());
		Integer countNum = wOrderService.findByReceiptCount(orderVo);
		Float totalPrice = 0f;
		if (countNum != 0) {
			WOrderCategoryVo orderCategoryVo = new WOrderCategoryVo();
			orderCategoryVo.setReceiptId(userVo.getbId());
			totalPrice = wOrderCategoryService.findByTotalPriceCount(orderCategoryVo);
		}
		
		result.put("countNum", countNum);
		result.put("totalPrice", totalPrice);
        return JSON.toJSONString(result);
	}
	
	/**
	 * 回收员个人资料
	 * @param v
	 * @return
	 */
	@RequestMapping("/toUser.do")
	public ModelAndView toUser(UserVo v) throws Exception {
		ModelAndView mv = new ModelAndView("/wx/seller/mine");
		UserVo userVo = userService.findByUsername(v);
		
		mv.addObject("userVo",userVo);
		return mv;
	}
	
	/**
	 * 小程序返回回收员个人资料
	 * @param v
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/toHomeUser.do")
    public  String toHomeUser(UserVo v) throws Exception {
		Map<String,Object> result = new HashMap<String, Object>();
		UserVo userVo = userService.findByUsername(v);
		
		//查询是否设置支付密码 1 设置 2未设置
		PayPassVo passVo = payPassService.findByPayUserId(userVo.getbId());
		if (passVo != null) {
			userVo.setPayStatus(1);
		}else {
			userVo.setPayStatus(2);
		}
		
		//用户银行卡信息
		BankcardInfoVo bankcardInfoVo = new BankcardInfoVo();
		bankcardInfoVo.setUserId(userVo.getbId());
		BankcardInfoVo bankcardInfo = bankcardInfoService.findByBankcardInfo(bankcardInfoVo);
		if (bankcardInfo != null) {
			result.put("bankcardInfoVo", bankcardInfo);
		}else {
			result.put("bankcardInfoVo", "1");
		}
		result.put("userVo", userVo);
		
		return JSON.toJSONString(result);
	}
	
	/**
	 * 修改手机号 ---短信验证码
	 * @param request
	 * @param v
	 * @return
	 * @throws ClientException
	 */
	@ResponseBody
	@RequestMapping(value = "/toSmsMessage.do")
	public AjaxResult<String> toSmsMessage(UserVo v) throws Exception {
		AjaxResult<String> ajaxResult = new AjaxResult<String>();
		
		SmsVo smsVo = new SmsVo();
		smsVo.setPhone(v.getTelephone());
		smsVo.setStatus(1);
		Integer count = smsService.findBySmsCount(smsVo);
		if (count < 5) {
			UserVo userVo = userService.findByUsername(v);
	        if (userVo != null) {
	        	ajaxResult.setMsg("2");
	        }else {
	        	SmsVo sms = SmsMessage.sendSms(v.getTelephone());
	        	sms.setStatus(1);
	        	smsService.save(sms);
	    		ajaxResult.setMsg(sms.getCode());
	        }
		}else {
			ajaxResult.setMsg("3");
		}
		return ajaxResult;
	}
	
	/**
	 * 获取---短信验证码
	 * @param request
	 * @param v
	 * @return
	 * @throws ClientException
	 */
	@ResponseBody
	@RequestMapping(value = "/toObtainMessage.do")
	public AjaxResult<String> toObtainMessage(UserVo v) throws Exception {
		AjaxResult<String> ajaxResult = new AjaxResult<String>();
		
		SmsVo smsVo = new SmsVo();
		smsVo.setPhone(v.getTelephone());
		smsVo.setStatus(1);
		Integer count = smsService.findBySmsCount(smsVo);
		if (count < 5) {
        	SmsVo sms = SmsMessage.sendSms(v.getTelephone());
        	sms.setStatus(1);
        	smsService.save(sms);
    		ajaxResult.setMsg(sms.getCode());
		}else {
			ajaxResult.setMsg("3");
		}
		return ajaxResult;
	}
	
	/**
	 * 手机号，短信验证码校验
	 * @param request
	 * @param session
	 * @param v
	 * @return
	 * @throws ClientException
	 */
	@ResponseBody
	@RequestMapping(value = "/toVerifyCode.do")
	public AjaxResult<String> toVerifyCode(SmsVo v,String userId) throws Exception  {
		AjaxResult<String> ajaxResult = new AjaxResult<String>();
		v.setStatus(1);
		List<SmsVo> smsVo = smsService.findPhone(v);
		if (smsVo.size()>0) {
			if (smsVo.get(smsVo.size()-1).getPhone().equals(v.getPhone())) {
				if (v.getCode().equals(smsVo.get(smsVo.size()-1).getCode())) {
					UserVo userVo = userService.find(new BigInteger(userId));
					
					userVo.setTelephone(v.getPhone());
					userService.updateUser(userVo);
					
					ajaxResult.setMsg("1");
				}else {
					ajaxResult.setMsg("2");
				}
			}else {
				ajaxResult.setMsg("3");
			}
		}else {
			ajaxResult.setMsg("4");
		}
		return ajaxResult;
	}
	
	/**
	 * 商家修改基础信息
	 * @param v
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/toUpdateUser.do")
	public AjaxResult<String> toUpdateUser(UserVo v) throws Exception {
		AjaxResult<String> ajaxResult = new AjaxResult<String>();
		UserVo user = userService.find(v.getId());
		
		if (v.getProvince() != null) {
			user.setProvince(v.getProvince());
		}
		if (v.getCity() != null) {
			user.setCity(v.getCity().replaceAll(" ", ""));
		}
		if (v.getArea() != null) {
			user.setArea(v.getArea().replaceAll(" ", ""));
		}
		if (v.getAddress() != null) {
			user.setAddress(v.getAddress());
		}
		if (v.getContacts() != null) {
			user.setContacts(v.getContacts());
		}
		if (v.getTelephone() != null) {
			user.setTelephone(v.getTelephone());
		}
		if (v.getLat() != null) {
			user.setLat(v.getLat());
		}
		if (v.getLng() != null) {
			user.setLng(v.getLng());
		}
		
		String id = userService.updateUser(user);
		ajaxResult.setMsg(id);
		return ajaxResult;
	}
	
	/**
	 * 进入确定支付方式页面
	 * @param v
	 * @return
	 */
	@RequestMapping("/toPayment.do")
	public ModelAndView toPayment(WOrderVo v,Float total) throws Exception {
		ModelAndView mv = new ModelAndView("/wx/seller/payment");

		WOrderVo orderVo = wOrderService.find(v.getId());
		//进行中
		orderVo.setStatus(1);
		//未支付
		orderVo.setPaymentStatus(2);
		//更新
		wOrderService.updateStatus(orderVo);
		
		mv.addObject("orderVo",orderVo);
		mv.addObject("total",total);
		return mv;
	}
	
	/**
	 * 验证openid 是否存在，不存在新增
	 * @param jsonObject
	 * @return
	 */
	public UserVo getOpenId(JSONObject jsonObject) throws Exception {
		//获取openid
		String openId = jsonObject.getString("openid");
		System.out.println("openid-------" + openId);
		//昵称
		String nickName = jsonObject.getString("nickName");
		//头像
		String avatarUrl = jsonObject.getString("avatarUrl");
				
		UserVo user = new UserVo();
		user.setWxOpenId(openId);
		//user.setWxType(3);
		user = userService.findByUsername(user);
		if (user == null ) {
			user = new UserVo();
			user.setWxOpenId(openId);
			user.setWxType(3);
			user.setStatus(1);
			user.setUserImg(avatarUrl);
			user.setNickName(nickName);
			user.setAuditStatus(1);
			userService.save(user);
		}
		return user;
	}
	
	/**
	 * 小程序查询用户是否注册
	 */
	@ResponseBody
	@RequestMapping("/toCheckUser.do")
	public String toCheckUser(HttpServletRequest request,UserVo v) throws Exception {
		Map<String,Object> result = new HashMap<String, Object>();
		
		//根据code 获取openid
		String code = request.getParameter("code");
		
		String codeUrl = "https://api.weixin.qq.com/sns/jscode2session?appid="+Constants.APPID_XCX+"&secret="+Constants.APPSECRET_XCX+"&js_code="+code+"&grant_type=authorization_code";
		JSONObject jsonObjectCode = WeiXinUtils.httpRequest(codeUrl, "GET", new JSONObject());
		System.out.println(jsonObjectCode);
		
		String openId = jsonObjectCode.getString("openid");
		
		UserVo user = new UserVo();
		user.setWxOpenId(openId);
		//user.setWxType(3);
		
		UserVo userVo = userService.findByUserOpenid(user);
		result.put("userVo", userVo);
		result.put("openId", openId);
		return JSON.toJSONString(result);
	}
	
	/**
	 * 小程序注册用户
	 * @param request
	 * @param v
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/openRegisterUser.do")
    public  String openRegisterUser(UserVo v,String openId) throws Exception {
		Map<String,Object> result = new HashMap<String, Object>();
		
		//判断用户手机号是否注册
		if (v.getTelephone() != null && v.getTelephone() != "") {
			UserVo user2 = new UserVo();
			user2.setTelephone(v.getTelephone());
			user2.setWxType(0);
			user2 = userService.findByUsername(user2);
			if (user2 != null) {
				result.put("msg", "2");
				return JSON.toJSONString(result);
			}
		}
		
		UserVo user = new UserVo();
		user.setWxOpenId(openId);
		user = userService.findByUserOpenid(user);
		if (user == null ) {
			user = new UserVo();
			user.setWxOpenId(openId);
			user.setWxType(0);
			user.setStatus(1);
			user.setAuditStatus(1);
			user.setContacts(v.getContacts());
			user.setTelephone(v.getTelephone());
			user.setProvince(v.getProvince());
			user.setCity(v.getCity());
			user.setArea(v.getArea());
			user.setAddress(v.getAddress());
			user.setLat(v.getLat());
			user.setLng(v.getLng());
			
			userService.save(user);
			user.setbId(user.getId().toString());
			
			//创建个人账户
			AccountVo account = new AccountVo();
			account.setUserId(user.getId().toString());
			account.setAmount(0f);
			accountService.save(account);
			
		}
		result.put("userVo", user);
		return JSON.toJSONString(result);
	}
	
	/**
	 * 小程序身份证图片上传
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping("/uploadFile.do")
	public String uploadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("进入uploadFile方法！");
        Map<String,Object> result = new HashMap<String, Object>();
        
        //获取文件需要上传到的路径
        String pathUrl = request.getSession().getServletContext().getRealPath("/")+("fileImage/");
        
        String userId = "";
        File dir = new File(pathUrl);
        if (!dir.exists()) {
            dir.mkdir();
        }

        request.setCharacterEncoding("utf-8");  //设置编码
        //获得磁盘文件条目工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //如果没以下两行设置的话,上传大的文件会占用很多内存，
        //设置暂时存放的存储室,这个存储室可以和最终存储文件的目录不同
        /**
         * 原理: 它是先存到暂时存储室，然后再真正写到对应目录的硬盘上，
         * 按理来说当上传一个文件时，其实是上传了两份，第一个是以 .tem 格式的
         * 然后再将其真正写到对应目录的硬盘上
         */
        factory.setRepository(dir);
        //设置缓存的大小，当上传文件的容量超过该缓存时，直接放到暂时存储室
        factory.setSizeThreshold(1024 * 1024);
        //高水平的API文件上传处理
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> list = upload.parseRequest(request);
            FileItem picture = null;
            for (FileItem item : list) {
                //获取表单的属性名字
                String name = item.getFieldName();
                //如果获取的表单信息是普通的 文本 信息
                if (item.isFormField()) {
                    //获取用户具体输入的字符串
                    userId = item.getString();
                    
                    System.out.println("name------"+name);
                    System.out.println("userId------"+userId);
                } else {
                    picture = item;
                }
            }
            //获取文件名称
			String originFileName = picture.getName();
			//获取图片后缀
			String suffix = FileType.getSuffixByFilename(originFileName);
            //重命名
            String targetFileName = (new Date()).getTime() + suffix;

            //真正写到磁盘上
            File file = new File(pathUrl + targetFileName);
            
            OutputStream out = new FileOutputStream(file);
            InputStream in = picture.getInputStream();
            int length = 0;
            byte[] buf = new byte[1024];
            // in.read(buf) 每次读到的数据存放在buf 数组中
            while ((length = in.read(buf)) != -1) {
                //在buf数组中取出数据写到（输出流）磁盘上
                out.write(buf, 0, length);
            }
            in.close();
            out.close();
            
            //解析身份证信息
            JSONObject res_obj = CardUtils.getCard(pathUrl + targetFileName);
            
            String url = ImageOperation.encodeImageCard(targetFileName,pathUrl);
            
            if (res_obj != null) {
            	System.out.println("校验成功------");
            	//解析身份证
                JSONArray outputArray = res_obj.getJSONArray("outputs");
                String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
                JSONObject dataValueObj = JSON.parseObject(output);
                
            	//身份征号
                String cardNum = dataValueObj.getString("num");
                //地址
                String cardAddress = dataValueObj.getString("address");
                //性别
                String cardSex = dataValueObj.getString("sex");
                //姓名
                String cardName = dataValueObj.getString("name");
                //生日
                String cardBirth = dataValueObj.getString("birth");
                
                //添加身份证信息
                CardVo cardVo = new CardVo();
                cardVo.setUserId(userId);
                
                System.out.println("开始查询");
                CardVo card = cardService.findByCard(cardVo);
                if (card == null) {
                	card = new CardVo();
                }
                
                card.setCardNum(cardNum);
                card.setCardAddress(cardAddress);
                card.setCardSex(cardSex);
                card.setCardName(cardName);
                card.setCardBirth(cardBirth);
                card.setCardUrl(url);
                card.setUserId(userId);
                
                if (card.getId() != null) {
                	cardService.update(card.getId(), 1L, card);
                }else {
                	cardService.save(card);
                }
                result.put("cardVo", card);
                
            }else {
            	result.put("msg", "2");
            }
        } catch (FileUploadException e1) {
        } 
        
        return JSON.toJSONString(result);
    }
	
	/**
	 * 小程序行驶证图片上传
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping("/uploadDrivingFile.do")
	public String uploadDrivingFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("进入uploadFile方法！");
        Map<String,Object> result = new HashMap<String, Object>();
        
        //获取文件需要上传到的路径
        String pathUrl = request.getSession().getServletContext().getRealPath("/")+("fileImage/");
        
        String userId = "";
        File dir = new File(pathUrl);
        if (!dir.exists()) {
            dir.mkdir();
        }

        request.setCharacterEncoding("utf-8");  //设置编码
        //获得磁盘文件条目工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //如果没以下两行设置的话,上传大的文件会占用很多内存，
        //设置暂时存放的存储室,这个存储室可以和最终存储文件的目录不同
        /**
         * 原理: 它是先存到暂时存储室，然后再真正写到对应目录的硬盘上，
         * 按理来说当上传一个文件时，其实是上传了两份，第一个是以 .tem 格式的
         * 然后再将其真正写到对应目录的硬盘上
         */
        factory.setRepository(dir);
        //设置缓存的大小，当上传文件的容量超过该缓存时，直接放到暂时存储室
        factory.setSizeThreshold(1024 * 1024);
        //高水平的API文件上传处理
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> list = upload.parseRequest(request);
            FileItem picture = null;
            for (FileItem item : list) {
                //获取表单的属性名字
                //String name = item.getFieldName();
                //如果获取的表单信息是普通的 文本 信息
                if (item.isFormField()) {
                    //获取用户具体输入的字符串
                    userId = item.getString();
                    System.out.println("userId------"+userId);
                } else {
                    picture = item;
                }
            }
            //获取文件名称
			String originFileName = picture.getName();
			//获取图片后缀
			String suffix = FileType.getSuffixByFilename(originFileName);
            //重命名
            String targetFileName = (new Date()).getTime() + suffix;

            //真正写到磁盘上
            File file = new File(pathUrl + targetFileName);
            
            OutputStream out = new FileOutputStream(file);
            InputStream in = picture.getInputStream();
            int length = 0;
            byte[] buf = new byte[1024];
            // in.read(buf) 每次读到的数据存放在buf 数组中
            while ((length = in.read(buf)) != -1) {
                //在buf数组中取出数据写到（输出流）磁盘上
                out.write(buf, 0, length);
            }
            in.close();
            out.close();
            
            //解析身份证信息
            JSONObject res_obj = DrivingUtils.getDriving(pathUrl + targetFileName);
            
            String url = ImageOperation.encodeImageCard(targetFileName,pathUrl);
            
            if (res_obj != null) {
            	System.out.println("校验成功------");
            	//解析身份证
                JSONArray outputArray = res_obj.getJSONArray("outputs");
                String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
                JSONObject dataValueObj = JSON.parseObject(output);
                
                //姓名
                String owner = dataValueObj.getString("owner");
                //车牌
                String plateNum = dataValueObj.getString("plate_num");
                //类型
                String vehicleType = dataValueObj.getString("vehicle_type");
                //注册日期
                String registerDate = dataValueObj.getString("register_date");
                //发动机号码
                String engineNum = dataValueObj.getString("engine_num");
                //发证日期
                String issueDate = dataValueObj.getString("issue_date");
                //状态
                String useCharacter = dataValueObj.getString("use_character");
                //品牌
                String model = dataValueObj.getString("model");
                //车辆识别代码
                String vin = dataValueObj.getString("vin");
                //地址
                String address = dataValueObj.getString("addr");
                
                //添加身份证信息
                DrivingVo drivingVo = new DrivingVo();
                drivingVo.setUserId(userId);
                
                System.out.println("开始查询行驶证");
                DrivingVo driving = drivingService.findByDriving(drivingVo);
                
                if (driving == null) {
                	driving = new DrivingVo();
                }
                driving.setOwner(owner);
                driving.setPlateNum(plateNum);
                driving.setVehicletype(vehicleType);
                driving.setRegisterDate(registerDate);
                driving.setEngineNum(engineNum);
                driving.setIssueDate(issueDate);
                driving.setUseCharacter(useCharacter);
                driving.setModel(model);
                driving.setVin(vin);
                driving.setAddress(address);
                driving.setUrl(url);
                driving.setUserId(userId);
                
                if (driving.getId() != null) {
                	drivingService.update(driving.getId(), 1L, driving);
                }else {
                	drivingService.save(driving);
                }
                System.out.println("行驶证查询结果---"+JSON.toJSONString(driving));
                result.put("drivingVo", driving);
            }else {
            	result.put("msg", "2");
            }
        } catch (FileUploadException e1) {
        } catch (Exception e) {
        }
        return JSON.toJSONString(result);
    }
	
	/**
	 * 查询是否绑定银行卡
	 */
	@ResponseBody
	@RequestMapping("/toSerchBank.do")
	public String toSerchBank(BankcardInfoVo v) throws Exception {
        Map<String,Object> result = new HashMap<String, Object>();
        BankcardInfoVo bankcardInfoVo = bankcardInfoService.findByBankcardInfo(v);
        result.put("bankcardInfoVo", bankcardInfoVo);
        return JSON.toJSONString(result);
	}
	
	/**
	 * 绑定银行卡
	 * @param request
	 * @param response
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping("/saveBank.do")
	public String saveBank(BankcardInfoVo v) throws Exception {
        Map<String,Object> result = new HashMap<String, Object>();
        
        SmsVo sms = new SmsVo();
        sms.setPhone(v.getPhone());
        sms.setStatus(1);
        List<SmsVo> smsVo = smsService.findPhone(sms);
		if (smsVo.size() > 0) {
			if (smsVo.get(smsVo.size()-1).getPhone().equals(v.getPhone())) {
				if (v.getCode().equals(smsVo.get(smsVo.size()-1).getCode())) {
					BankcardInfoVo infoVo = new BankcardInfoVo();
			        infoVo.setUserId(v.getUserId());
			        //查询是否存在
			        BankcardInfoVo bankcardInfoVo = bankcardInfoService.findByBankcardInfo(infoVo);
			        if (bankcardInfoVo == null) {
			        	bankcardInfoVo = new BankcardInfoVo();
			        }
			        Map<String, String> querys = new HashMap<String, String>();
			        //银行卡号
			        querys.put("accountNo", v.getBankCardName());
			        //身份证号
				    querys.put("idCard", v.getCardNumber());
				    //手机号
				    querys.put("mobile", v.getPhone());
				    //所属人名称
				    querys.put("name", v.getBankName());
				    //返回银行卡信息
			        JSONObject jsonObject =  BankCardutils.getBankCard(querys);
			        //是否成功状态
			        String status = jsonObject.getString("status");
			        //String cardType = jsonObject.getString("cardType");
			        if (status.equals("01")) {
			        	//if (!cardType.equals("信用卡")) {
			        		//所属银行
				            String bankCardName = jsonObject.getString("bank");
				            //用户id
				            bankcardInfoVo.setUserId(v.getUserId());
				            //所属人
				            bankcardInfoVo.setBankName(v.getBankName());
				            //身份证号
				            bankcardInfoVo.setCardNumber(v.getCardNumber());
				            //电话号码
				            bankcardInfoVo.setPhone(v.getPhone());
				            //所属银行
				            bankcardInfoVo.setBankCardName(bankCardName);
				            //银行卡号
				            bankcardInfoVo.setBankCardNumber(v.getBankCardName());
				            
				            if (bankcardInfoVo.getId() != null) {
				            	bankcardInfoService.update(bankcardInfoVo.getId(), 1L, bankcardInfoVo);
				            }else {
				            	bankcardInfoService.save(bankcardInfoVo);
				            }
				            result.put("bankcardInfoVo", bankcardInfoVo);
				        	result.put("msg", "1");
			        	/*}else {
			        		result.put("msg", "5");
			        	}*/
			        }else {
			        	result.put("msg", "2");
			        }
				}
			}else {
				//验证码错误
				result.put("msg", "3");
			}
		}else {
			result.put("msg", "4");
		}
        
        return JSON.toJSONString(result);
    }
	
	/**
	 * 更改用户认证状态
	 */
	@ResponseBody
	@RequestMapping("/updateUserStatus.do")
	public String updateUserStatus(UserVo v) throws Exception {
		LOGGER.info("进入updateUserStatus方法！");
        Map<String,Object> result = new HashMap<String, Object>();
        //根据用户id查询，修改认证状态
        UserVo userVo = userService.find(new BigInteger(v.getbId()));
        userVo.setAuditStatus(3);
        userVo.setWxType(v.getWxType());
        userService.updateUser(userVo);
        result.put("msg", "1");
        return JSON.toJSONString(result);
	}
	
	/**
	 * 查询用户余额
	 * @param v
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/serchUserAccount.do")
	public String serchUserAccount(UserVo v) throws Exception {
		Map<String,Object> result = new HashMap<String, Object>();
		AccountVo accountVo = accountService.findByUserId(v.getbId());
		result.put("accountVo", accountVo);
		return JSON.toJSONString(result);
	}
	
	/**
	 * 意见反馈
	 * @param v
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("/opinionAdd.do")
	public String opinionAdd(OpinionVo v) throws Exception {
        LOGGER.info("进入opinionAdd方法！");
        Map<String,Object> result = new HashMap<String, Object>();
        opinionService.save(v);
        
        result.put("msg", "1");
        return JSON.toJSONString(result);
	}
	
	/**
	 * 设置支付密码校验
	 * 
	 */
	@ResponseBody
	@RequestMapping("/checkPay.do")
	public String checkPay(UserVo v) throws Exception {
		Map<String,Object> result = new HashMap<String, Object>();
		UserVo user = userService.findByUsername(v);
		if (user != null) {
			SmsVo sms = new SmsVo();
	        sms.setPhone(v.getTelephone());
	        sms.setStatus(1);
	        List<SmsVo> smsVo = smsService.findPhone(sms);
	        if (smsVo.size() > 0) {
	        	if (user.getCardName().equals(v.getCardName()) 
						&& user.getCardNum().equals(v.getCardNum()) 
						&& user.getTelephone().equals(v.getTelephone())
						&& smsVo.get(smsVo.size()-1).getPhone().equals(v.getTelephone())
						&& smsVo.get(smsVo.size()-1).getCode().equals(v.getCode())) {
					result.put("msg", "1");
				}else {
					result.put("msg", "2");
				}
	        }else {
	        	result.put("msg", "3");
	        }
 		}
        return JSON.toJSONString(result);
	}
	
	/**
	 * 新增/忘记支付密码
	 * @param v
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("/setPay.do")
	public String setPay(PayPassVo v) throws Exception {
		Map<String,Object> result = new HashMap<String, Object>();
		PayPassVo  passVo = payPassService.findByPayUserId(v.getUserId());
		if (passVo != null) {
			if (passVo.getUserId().equals(v.getUserId())) {
				passVo.setPassword(Utils.md5(v.getPassword(), Constants.PAY_PASS_CACHE_KEY));
				payPassService.update(passVo.getId(), 1L, passVo);
			}
		}else {
			v.setPassword(Utils.md5(v.getPassword(), Constants.PAY_PASS_CACHE_KEY));
			payPassService.save(v);
		}
		result.put("msg", "1");
        return JSON.toJSONString(result);
	}
	
	/**
	 * 校验支付密码是否正确
	 * @param v
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/checkPayPad.do")
	public String checkPayPad(PayPassVo v) throws Exception {
		Map<String,Object> result = new HashMap<String, Object>();
		PayPassVo  passVo = payPassService.findByPayUserId(v.getUserId());
		if (passVo != null) {
			String password = Utils.md5(v.getPwdPass(), Constants.PAY_PASS_CACHE_KEY);
			if (passVo.getPassword().equals(password)) {
				result.put("msg", "1");
			}else {
				result.put("msg", "2");
			}
		}
        return JSON.toJSONString(result);
	}
	
	/**
	 * 修改支付密码
	 * @param v
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("/setUpdatePay.do")
	public String setUpdatePay(PayPassVo v) throws Exception {
		Map<String,Object> result = new HashMap<String, Object>();
		PayPassVo  passVo = payPassService.findByPayUserId(v.getUserId());
		if (passVo != null) {
			String password = Utils.md5(v.getPwdPass(), Constants.PAY_PASS_CACHE_KEY);
			if (passVo.getPassword().equals(password)) {
				passVo.setPassword(Utils.md5(v.getPassword(), Constants.PAY_PASS_CACHE_KEY));
				payPassService.update(passVo.getId(), 1L, passVo);
				result.put("msg", "1");
			}else {
				result.put("msg", "2");
			}
		}
        return JSON.toJSONString(result);
	}
	
	/**
	 * 提现
	 */
	@ResponseBody
	@RequestMapping("/toPutForward.do")
	public String toPutForward(AccountVo v) throws Exception{
		Map<String,Object> result = new HashMap<String, Object>();
		
		PayPassVo  passVo = payPassService.findByPayUserId(v.getUserId());
		if (passVo != null) {
			String password = Utils.md5(v.getPassword(), Constants.PAY_PASS_CACHE_KEY);
			if (passVo.getPassword().equals(password)) {
				AccountVo accountVo = accountService.findByUserId(v.getUserId());
				if (accountVo != null) {
					//修改金额
					accountVo.setAmount(accountVo.getAmount() - v.getAmount());
					accountService.update(new BigInteger(accountVo.getbId()), 1L, accountVo);
					
					//用户银行卡信息
					BankcardInfoVo bankcardInfoVo = new BankcardInfoVo();
					bankcardInfoVo.setUserId(v.getUserId());
					BankcardInfoVo bankcardInfo = bankcardInfoService.findByBankcardInfo(bankcardInfoVo);
					
					//操作日志
					AccountLogVo logVo = new AccountLogVo();
					//账户之前余额
					logVo.setAmount(accountVo.getAmount());
					//金额
					logVo.setPrice(v.getAmount());
					//用户id
					logVo.setUserId(v.getUserId());
					//账户id
					logVo.setAccountId(accountVo.getbId());
					//类型 1 充值 2 提现 3 支出 4 收入
					logVo.setBusinessType("2");
					//提现操作状态，1 未操作 2 已操作
					logVo.setType(1);
					//业务编号
					logVo.setBusinessNumber(RandomUtils.random6());
					//所属人名称
					logVo.setBankName(bankcardInfo.getBankName());
					//手机号
					logVo.setPhone(bankcardInfo.getPhone());
					//所属支行
					logVo.setBankCardName(bankcardInfo.getBankCardName());
					//银行卡号
					logVo.setBankCardNumber(bankcardInfo.getBankCardNumber());
					
					//日志
					accountLogService.save(logVo);
					
					result.put("msg", "1");
					result.put("bankcardInfoVo", logVo);
				}
			}else {
				result.put("msg", "2");
			}
		}else {
			result.put("msg", "4");
		}
		return JSON.toJSONString(result);
	}

}
